/*
 * Copyright (C) 2018 Weibo, Inc. All Rights Reserved.
 */
package com.fzy.common.entity;


import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fzy.common.enums.ErrorCode;
import lombok.Data;

import java.io.Serializable;

/**
 * 接口API公共返回值
 *
 * @author zhaoyang10
 * @date 2018/7/18 上午10:19
 */
@Data
public class ApiResult<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private Integer code;

    private String message;

    /**
     * 不要加transient,加了序列化时不会序列化data属性！！！
     */
    private T data;

    public ApiResult() {
    }

    public ApiResult(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    public ApiResult(T data) {
        this.code = ErrorCode.SUCCESS.getCode();
        this.message = ErrorCode.SUCCESS.getMsg();
        this.data = data;
    }

    public ApiResult(Integer code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static <T> ApiResult<T> ok() {
        return new ApiResult<>(0, "success");
    }

    public static <T> ApiResult<T> ok(T data) {
        return new ApiResult<>(data);
    }

    public static <T> ApiResult<T> failed(ErrorCode errorCode) {
        return new ApiResult<>(errorCode.getCode(), errorCode.getMsg());
    }

    public static <T> ApiResult<T> failed(Integer code, String msg) {
        return new ApiResult<>(code, msg);
    }

    /**
     * 判断请求是否成功 true 成功, false 失败
     */
    @JsonIgnore
    public boolean hasSuccess() {
        return null != this.code && ErrorCode.SUCCESS.getCode() == this.code;
    }

}
